package model

import (
	"gorm.io/gorm"
	"service/basic/config"
	"time"
)

type Class struct {
	Id        uint           `gorm:"column:id;type:int UNSIGNED;primaryKey;not null;" json:"id"`
	Title     string         `gorm:"column:title;type:varchar(255);comment:课程标题;not null;" json:"title"`                         // 课程标题
	Info      string         `gorm:"column:info;type:varchar(255);comment:视频简介;not null;" json:"info"`                           // 视频简介
	CoverUrl  string         `gorm:"column:cover_url;type:varchar(255);comment:视频封面;not null;" json:"cover_url"`                 // 视频封面
	VideoUrl  string         `gorm:"column:video_url;type:varchar(255);comment:视频播放地址;not null;" json:"video_url"`             // 视频播放地址
	VipPrice  float64        `gorm:"column:vip_price;type:decimal(10, 2);comment:会员价;not null;default:0.00;" json:"vip_price"`    // 会员价
	Price     float64        `gorm:"column:price;type:decimal(10, 2);comment:原价;not null;default:0.00;" json:"price"`              // 原价
	TypesId   uint           `gorm:"column:types_id;type:int UNSIGNED;comment:分类id;not null;default:1;" json:"types_id"`           // 分类id
	Status    uint           `gorm:"column:status;type:int UNSIGNED;comment:状态:1未购买 2已购买;not null;default:1;" json:"status"` // 状态:1未购买 2已购买
	CreatedAt time.Time      `gorm:"column:created_at;type:datetime(3);not null;default:CURRENT_TIMESTAMP(3);" json:"created_at"`
	UpdatedAt time.Time      `gorm:"column:updated_at;type:datetime(3);not null;default:CURRENT_TIMESTAMP(3);" json:"updated_at"`
	DeletedAt gorm.DeletedAt `gorm:"column:deleted_at;type:datetime(3);default:NULL;" json:"deleted_at"`
}

func (c *Class) TableName() string {
	return "class"
}

// 列表
func (c *Class) ListPage(page, pageSize int64) (classList []*Class, err error) {
	err = config.DB.Scopes(Paginate(int(page), int(pageSize))).Find(&classList).Error
	return
}

// 分页
func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		if page <= 0 {
			page = 1
		}
		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}

		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}

// 筛选课程
func (c *Class) ListType() (claList []*Class, err error) {
	err = config.DB.Where("types_id = ?", c.TypesId).Find(&claList).Error
	return
}

// 课程详情
func (c *Class) Detail() error {
	return config.DB.Where("id = ?", c.Id).Limit(1).Find(&c).Error
}

// 查询状态
func (c *Class) GetStatus() error {
	return config.DB.Where("status = ?", c.Status).Limit(1).Find(&c).Error
}
